package pacman.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Properties;

public class ScoreTableLoader {
    private Properties prop;
    private Hashtable<String, String> table;
    private String filePath;

    public ScoreTableLoader(String filePath) throws FileNotFoundException, IOException {
		prop = new Properties();
		prop.load(new FileInputStream(filePath));
		this.filePath = filePath;
		table = new Hashtable<String, String>();
		for (Object element : prop.keySet()) {
		    table.put(element.toString(), prop.getProperty(element.toString()));
		}
    }

    public ArrayList<ScoreRecord> loadScoreTable() {
		ArrayList<ScoreRecord> srs = new ArrayList<ScoreRecord>();
		for (String key : table.keySet()) {
		    String value = table.get(key);
		    ScoreRecord sr = new ScoreRecord(key, new Integer(value));
		    srs.add(sr);
		}
		Collections.sort(srs);
		return srs;
    }

    public boolean saveScoreTable(ArrayList<ScoreRecord> scores) {
		if (scores == null) return false;
		boolean result = true;
	
		Hashtable<String, String> towrite = new Hashtable<String, String>();	
		for (ScoreRecord scoreRecord : scores) {
		    towrite.put(scoreRecord.getName(), scoreRecord.getPoints() .toString());
		}
		prop.putAll(towrite);
		try {
		    prop.store(new FileOutputStream(filePath), null);
		 } catch (Exception e) {
			 System.out.println(e.getMessage());
		 }
		return result;
    }
}
